<template>
  <div>
    <div>
      <el-button icon="el-icon-plus" circle size="small" @click="openUserDialog"></el-button>
    </div>
    <div>
      <el-tag v-for="(item, index) in selectedUsers" :key="item.code" closable @close="handleClose(index)" class="user-tag">{{ item.name }}</el-tag>
    </div>

    <user-table ref="userTable" :multiple-mode="multipleMode" @set-value="setUsers"></user-table>
  </div>
</template>

<script>
import UserTable from "./userTable";

export default {
  name: "UserSelector",
  components: {
    UserTable
  },
  props: {
    value: {
      type: Array,
      default: []
    },
    multipleMode: {
      type: Boolean,
      default: true
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      selectedUsers: this.value
    }
  },
  methods: {
    openUserDialog() {
      this.$refs.userTable.init(this.cloneValue(this.selectedUsers));
    },
    handleClose(index) {
      this.selectedUsers.splice(index, 1);
      this.$emit("change", this.selectedUsers);
    },
    setUsers(users) {
      this.selectedUsers = users;
      this.$emit("change", this.selectedUsers);
    },
    cloneValue(value) {
      return this.$lodash.clone(value);
    }
  },
  watch: {
    value: {
      handler(val) {
        this.selectedUsers = val;
      },
      deep: true
    }
  }
}
</script>

<style scoped lang="scss">
  .el-button--small {
    font-size: 16px;

    &.is-circle {
      padding: 6px;
    }
  }

  .user-tag {
    margin-right: 8px;
  }
</style>
